<template>
  <div class="app-container">
    <div
      v-if="isShowFilterContainer"
      class="filter-container"
    >
      <el-input
        v-model="pagerequest.keyword"
        :placeholder="L(keywordPlaceholder)"
        style="width: 200px;"
        class="filter-item"
      />

      <slot name="FilterItems" />

      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getpage"
      >
        {{ L('Find') }}
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="create"
      >
        {{ L('Add') }}
      </el-button>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="tableSortChange"
      >

        <slot name="TableColumns" />

        <el-table-column
          v-if="isShowEditDeleteButton"
          :label="L('Actions')"
        >
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="edit(scope.row)"
            >{{ L('Edit') }}</el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteItem(scope.row)"
            >{{ L('Delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="datatable-paging">
      <el-pagination
        :page-sizes="[10, 50, 100, 150]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="pagesizeChange"
        @current-change="pageChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogCreateOrEditVisible"
      :width="dialogWidth"
      modal
      class="dialog-layout"
      modal-append-to-body
      append-to-body
      lock-scroll
      show-close
      :close-on-click-modal="false"
    >
      <slot
        v-loading="dialogLoading"
        name="CreateOrEditDialog"
        :dialogAction="dialogAction"
      />

      <div slot="footer">
        <el-button @click="closeDialog">{{ L('Cancel') }}</el-button>
        <el-button
          type="primary"
          @click="saveDialog"
        >{{ L('OK') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import PagedFilterAndSortedRequest from '@/store/entities/pagedFilterAndSortedRequest'

export default {
  name: 'CRUD',
  directives: { waves },
  props: {
    entityName: {
      type: String,
      default: ''
    },
    requestParam: {
      type: Object,
      default: () => { return {} }
    },
    keywordPlaceholder: {
      type: String,
      default: 'Keyword'
    },
    isShowFilterContainer: {
      type: Boolean,
      default: true
    },
    isShowEditDeleteButton: {
      type: Boolean,
      default: true
    },

    dialogWidth: {
      type: String,
      default: '500px'
    },
    dialogCreateEnityParam: {
      type: Object,
      default: () => { return {} }
    },
    dialogEnity: {
      type: Object,
      default: () => { return {} }
    },
    dialogCreateTitle: {
      type: String,
      default: 'Create'
    },
    dialogEditTitle: {
      type: String,
      default: 'Edit'
    },
    deleteConfirm: {
      type: String,
      default: 'DeleteConfirm'
    }
  },
  data() {
    return {
      pagerequest: { ...PagedFilterAndSortedRequest },
      activeSelected: null,
      creationTime: [],

      dialogCreateOrEditVisible: false,
      dialogAction: '',
      dialogLoading: false
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogAction === 'create' ? this.L(this.dialogCreateTitle) : this.L(this.dialogEditTitle)
    },
    list() {
      return this.$store.state[this.entityName].list
    },
    totalCount() {
      return this.$store.state[this.entityName].totalCount
    },
    currentPage() {
      return this.$store.state[this.entityName].currentPage
    },
    pageSize() {
      return this.$store.state[this.entityName].pageSize
    },
    loading() {
      return this.$store.state[this.entityName].loading
    }
  },
  async created() {
    this.$store.commit(`${this.entityName}/SET_ENTITY_NAME`, this.entityName)
    this.getpage()
  },
  methods: {
    tableSortChange(column) {
      this.pageChange(1)
      if (column.order === 'descending') {
        this.pagerequest.sorting = `${column.prop} desc`
      } else {
        this.pagerequest.sorting = `${column.prop} asc`
      }
      this.getpage()
    },
    edit(row) {
      this.openDialog(row, 'edit')
    },
    create() {
      this.openDialog(this.dialogCreateEnityParam, 'create')
    },
    async deleteItem(row) {
      this.$confirm(this.L(this.deleteConfirm), this.L('Tips'), {
        confirmButtonText: this.L('Yes'),
        cancelButtonText: this.L('No'),
        type: 'warning'
      })
        .then(async() => {
          await this.$store.dispatch({
            type: `${this.entityName}/deleteItem`,
            data: row
          })
          await this.getpage()
          this.$message({
            type: 'success',
            message: this.L('DeleteSuccessfully')
          })
        })
    },
    async getpage() {
      this.pagerequest.maxResultCount = this.pageSize
      this.pagerequest.skipCount = (this.currentPage - 1) * this.pageSize
      // filters
      for (var i in this.requestParam) {
        this.pagerequest[i] = this.requestParam[i]
      }

      await this.$store.dispatch({
        type: `${this.entityName}/getAll`,
        data: this.pagerequest
      })
    },
    pageChange(page) {
      this.$store.commit(`${this.entityName}/SET_CURRENT_PAGE`, page)
      this.getpage()
    },
    pagesizeChange(pagesize) {
      this.$store.commit(`${this.entityName}/SET_PAGE_SIZE`, pagesize)
      this.getpage()
    },

    // 添加编辑对话框方法
    openDialog(enity, action) {
      this.dialogCreateOrEditVisible = true
      var temp = Object.assign({}, enity) // copy obj
      this.$emit('update:dialogEnity', temp)
      this.dialogAction = action
      // 回调表单验证清除
      this.$nextTick(function() {
        this.$emit('dialogFormClearValidate')
        // this.$refs[`${this.entityName}Form`].clearValidate()
      })
    },
    closeDialog() {
      this.dialogCreateOrEditVisible = false
    },
    saveDialog() {
      if (!!this.dialogEnity.id && this.dialogAction === 'edit') {
        this.$emit('dialogFormValidate', async val => {
          if (val) {
            this.dialogLoading = true
            await this.$store.dispatch({
              type: `${this.entityName}/update`,
              data: this.dialogEnity
            })
            this.dialogLoading = false
            this.$message({
              type: 'success',
              message: this.L('SavedSuccessfully')
            })
            this.getpage()
            this.closeDialog()
          }
        })
      } else {
        this.$emit('dialogFormValidate', async val => {
          if (val) {
            this.dialogLoading = true
            await this.$store.dispatch({
              type: `${this.entityName}/create`,
              data: this.dialogEnity
            })
            this.dialogLoading = false
            this.getpage()
            this.closeDialog()
          }
        })
      }
    }
  }
}
</script>
